<?php

// +----------------------------------------------------------------------
// |仓库服务层
// +----------------------------------------------------------------------

namespace app\Api\system;

use think\facade\Validate;
use think\facade\Db;
use think\facade\Cache;
use app\common\Model\ConfigModel;

class getGatherService
{   
     protected $configModel;
      public function __construct()
      {
          
          $this->configModel = new ConfigModel();
      }
      //获取采集数据
      public static function getGat(){    
        //获取到需要采集的数据
        $map['status']=['2'];
        $offerids=db::name('gatherproduct')->where($map)->find();
       
        if(empty($offerids)){
            echo "没有需要采集的数据";die;
        }
        $offId=$offerids['offerid'];   
        $data= self::getGather($offId);
     
        if($data['status']=='success'){
            $product_video=$data["datas"]['video_url'];
     
            $product_turnover=$data["datas"]['sale_count'];
            $memberid=$data["datas"]['memberid'];
            $main_imgs=$data["datas"]['main_imgs'];
            $compname=$data["datas"]['compname'];
     
            $productname=$data["datas"]['product_name'];
            if(!$memberid && $compname){     
                
                $m_url=Db::name('supplier')->where('name',$compname)->filrd('memberid,id,status')->find();
                if($m_url){
                    $compcode=$m_url['compcode'];
                    $memberid=$m_url['memberid'];
                    $code=rtrim(strtoupper(get_first_letter($compname)),"YXGS");//获取中文的首字母，并且转为大写      
                    $compid=$m_url['id'];;          
                }              
            }
            else{            
          
                $m_url=Db::name('supplier')->where('memberid',$memberid)->field('memberid,id,status')->find();

                if(empty($m_url)){
                    $supplier['name']= $compname;
                    $supplier['memberid']= $memberid;
                    $supplier['code']=  rtrim(strtoupper(get_first_letter($compname)),"YXGS");//获取中文的首字母，并且转为大写                  
                  
                    
                    $supplier['status']=1;
                    $supplier['createtime']=date('Y-m-d H:i:s');
                    $supplier['createymd']=date('Ymd');
                        
                    $supplier_id=Db::name('supplier')->insertGetId($supplier);
                 
                     $code= $supplier['code'];
                    $compid=$supplier_id;
                 
                    
                }else{
                    $memberid=$m_url['memberid'];
                    $code=rtrim(strtoupper(get_first_letter($compname)),"YXGS");//获取中文的首字母，并且转为大写      
                    $compid=$m_url['id'];;      
                }
                
            }
            $localsku= mb_substr($code,0,3).substr((string)time(), -2);
            $m_url=Db::name('supplier')->where('memberid',$memberid)->field('memberid,id,status')->find();

            $data['datas']["child"]= $data["child"];
            if($data['status']!='false' && $m_url['status']==1 ){
            
                unset($data["datas"]['memberid'],$data["datas"]['compname'],$data["datas"]['skug_name'],$data["datas"]['main_imgs'],$data["datas"]['product_name']);
                $datas=json_encode($data["datas"],JSON_UNESCAPED_UNICODE);
                $res=Db::name('gatherproduct')->where('offerid',$offId)->update(array('turnover'=>$product_turnover,'video'=>$product_video,'status'=>'3','memberid'=>$memberid,'compname'=>$compname,'name'=>$productname,'datas'=>$datas,'main_imgs'=>$main_imgs,'compid'=>$compid,'compcode'=>$code,'localsku'=>$localsku));
            }elseif($m_url['status']==0){
                  
                Db::name('gatherproduct')->where('offerid',$offId)->update(array('status'=>'5'));
            }else{
               
                Db::name('gatherproduct')->where('offerid',$offId)->update(array('status'=>'-1'));
            }

        }
        
        return  json_encode($data,JSON_UNESCAPED_UNICODE);
     }


     //采集数据
      public static function getGather($offId){
                // 云市场分配的密钥Id
        $secretId = "AKID5icrjtx9490vc16cbh25oac14qejenu1itcp";
        // 云市场分配的密钥Key
        $secretKey = "jBrUvp6vV4lk7c8u4vAp7rm9p310wUv0whVKtZ3";        
        $source = 'market';
          // 签名
        $datetime = gmdate('D, d M Y H:i:s T');
        $signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
        $sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
        $auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);       
        // 请求头
        $headers = array(
            'X-Source' => $source,
            'X-Date' => $datetime,
            'Authorization' => $auth,
        );
        // 查询参数
        $queryParams = array (
            'item_id' => $offId,
        );

        // body参数（POST方法下）
        $bodyParams = array ();
        // url参数拼接
        $url = 'https://service-own4gxsw-1306861247.gz.apigw.tencentcs.com/release/api/1688/item_detail/v2';
        if (count($queryParams) > 0) {
            $url .= '?' . http_build_query($queryParams);
        }
        $data=crul_get($url,$headers,$bodyParams);
        $result = json_decode($data, true);  
   
        if(isset($result['message'])){
             Db::name('gatherproduct')->where('offerid',$offId)->update(array('status'=>'-1','errmassage'=>$result['message']));
            echo $result['message'];die;
        }
        $results=$result["data"];      
         if (empty($result) || !isset($result['code'])) {
            $datas['datas']='';
            $datas['status']='false';
            $datas['offId']=$offId;
        }
        if ($result['code'] != 200) {
            $datas['datas']='';
            $datas['status']='false';
            $datas['offId']=$offId;
        }
        $product['memberid']=$results['shop_info']["seller_member_id"];//供应商唯一id
        $product['compname']=$results['shop_info']["shop_name"];//公司名称
        $product['product_name']=$results["title"];//产品标题
        $product['sku_name']=$product['skug_name']='';//货号，产品分类名


        foreach($results["product_props"]  as $k=>$v){//遍历产品特征


            if(array_keys($v)[0]=='产品类别'){
                $product['skug_name']=array_values($v)[0];//获取产品分类名称
            }
            if(array_keys($v)[0]=='货号'){
                $product['sku_name']=array_values($v)[0];//获取货号
            }
            if(array_keys($v)[0]=='商家编码' && $product['sku_name']=''){
                $product['sku_name']=array_values($v)[0];//获取货号
            }
            foreach ($v as $k1=>$val){
                $product['attr'][$k1]=$val;
            }

        }
    
        $product['video_url']=$results["video_url"];
        $product['main_imgs']=implode(',',$results["main_imgs"]);
        $product['sale_count']=$results["sale_count"];
        $product['sku_name']=str_replace(array(' ','|','\'',',','(',')','（','）','$','*','+','.','[',']','?','\\','^','{','}'),'',$product['sku_name']);

        $product['detailurl']=$results["detail_url"];//产品详情页链接地址
        $product['product_photo']=$results["main_imgs"][0]; 
       
        $product['price']=isset($results["price_info"]['price_max'])?$results["price_info"]['price_max']:$results["price_info"]['price'];
        $product['offerid']=$offId;

        $img=$child=[];

        if(isset($results['sku_props'][0])){
             foreach($results['sku_props'][0]['values'] as $v){
                $img[$v['name']]=$v['imageUrl'];
              }
            $product['option1']=$results['sku_props'][0]['prop_name']??'颜色';
            $product['option2']=$results['sku_props'][1]['prop_name']??'尺码';
        }else{
               $product['option1']='颜色';
              $product['option2']='尺码';
        }

        foreach($results["skus"] as $k=>$v){
            //2023年11月2号 去除颜色跟尺码
            $props_names=str_replace('尺码:','',str_replace('颜色:','',$v['props_names']));
         
             if(strlen($props_names)>60){
                continue ;
            }
           
            $child[(string)$v["skuid"]]['price']=isset($v['origin_price'])?$v['origin_price']:$product['price'];
            $child[(string)$v["skuid"]]['skuid']=$v['skuid'];
            $child[(string)$v["skuid"]]['img']='';
       
            $child[(string)$v["skuid"]]['skuattr']= explode(';',$props_names);
            $attr_array=explode(';',$props_names);
             
             
            if(isset($img[$attr_array[0]])){
                if($product['product_photo']==''){
                    $product['product_photo'] = $img[$attr_array[0]];
                }
                $child[(string)$v["skuid"]]['img']=$img[$attr_array[0]];
            }else{
                $child[(string)$v["skuid"]]['img']=$product['product_photo'];
            }

        }
  
        $datas['datas']=$product;
        $datas['child']=$child;
        $datas['status']='success';
        $datas['offId']=$offId;
        return $datas;
        
     }


     //生成条形码
      public static function createBarCode(){
           $count=Db::name('code')->where('is_user','1')->count();
           if($count<1000){
                //小于1000条未使用code，生成新的code
                $code = '';
                $prefix = 'B'.self:: getRand(5);
                for($i=0;$i<20000;$i++)
                {
                    $code .= $prefix.self:: getRand().',';
                }
            
                $code = substr($code,0,-1);
                $arr = explode(',', $code);
                $arr = array_unique($arr);
              $data = [];
                foreach ($arr as $code) {
                    $data[] = ['code' => $code];
                }

                 Db::name('code')->insertAll($data);
                $time = date('Y-m-d H:i:s',time());
                return $time . '生成pwin成功';
           }else{
              return  '条码的数量还没有小于1000,无需生成新的条码';
           }

      }
      // 随机数 生成
        public static function getRand($num = 4)
        {
            $arr = array('8','3','4','2','7','9','5','6','1');
            $rand = '';
            for($i=0;$i<$num;$i++)
            {
                $key = mt_rand(0,8);
                $rand .= $arr[$key];
            }
            
            return $rand;
        }
   
        //创建产品
        public static function creatupdate(){
          $gather=Db::name('gatherproduct')->where('status','3')->find();
           if($gather){
              Db::startTrans();
            try{
                $code=Db::name('code')->where('is_user','1')->find();
                $codes['is_user']=0;
                Db::name('code')->where('code', $code['code'])->update($codes);
                $parent_data=$data=$datas=array();  
                $product_datas=json_decode($gather['datas'],true);     
                  if(isset($product_datas['attr'])){
                     $attr= json_encode($product_datas['attr'],JSON_UNESCAPED_UNICODE);
                  }else{
                      $attr='';
                  }                
                 
                  $localsku= mb_substr($gather['localsku'],0,3).substr((string)time(), -2);
                $counts=count($product_datas['child']);
                $parent_data['offerid'] = $gather['offerid'];
                $parent_data['turnover'] = $gather['turnover'];
                //先查询款号在产品表这里存不存在
                $parent_data['localsku']=$local=self::checksku($localsku);
                $parent_data['createtime']=date('Y-m-d H:i:s');
                // $parent_data['name_En']=self::youdao($gather['name']);        
                $parent_data['createymd']=date('Ymd');
                $parent_data['title']=$gather['name'];
                $parent_data['img']=$pic=$product_datas['product_photo'];
                $parent_data['supplier_id']=$gather['compid'];
                $parent_data['supplier_name']=$gather['compname'];
                $parent_data['status']=1;    
                $parent_data['imgarr']=$gather['main_imgs'];
                $parent_data['attr']=$attr;
                $parent_data['price']=$product_datas['price'];
                $parent_data['code']=$code['code'];
                $parent_data['video']=$gather['video'];
                $parent_data['turnover']=$gather['turnover'];;
                $parent_data['offerid']=$gather['offerid'];
                $parent_data['detail_url']=$product_datas['detailurl'];
                $parent_data['c_id']=0;
                $parent_data['user_id']=$gather['user_id'];
                $parent_data['product_link']='https://detail.1688.com/offer/'.$gather['offerid'].'.html';
                $parent_data['option1']=$product_datas['option1']??'';
                $parent_data['option2']=$product_datas['option2']??'';
              
            $parent_id=Db::name('products')->insertGetId($parent_data);
            if($parent_id){
                //子集
                if($product_datas['child']){
                    foreach ($product_datas['child'] as $key){ 
                            if(empty($key['img'])){
                                if($counts==1){
                                    $data['img']=$product_datas['product_photo'];
                                }else{
                                    continue;
                                }
                            }else{
                               $data['img']=$key['img'];
                            } 
                        $localsku=$local;
                        //判断是不是数组
                        if($key['skuattr']){
                            if(is_array($key['skuattr'])){
                            foreach ($key['skuattr'] as $v){
                                $localsku .= '-'.$v;
                            }                                
                            }else{
                                $localsku .= '-'.$key['skuattr'];
                            }
                             $code=Db::name('code')->where('is_user','1')->find();
                            $codes['is_user']=0;
                            Db::name('code')->where('code', $code['code'])->update($codes);
                            $data['offerid'] = $gather['offerid'];
                            $data['turnover'] = $gather['turnover'];
                            //先查询款号在产品表这里存不存在
                            $data['localsku']=$localsku;
                            // $data['name_En']=self::youdao($gather['name']);  //英文翻译
                            $data['createtime']=date('Y-m-d H:i:s');
                            $data['createymd']=date('Ymd');
                            $data['title']=$gather['name'];             
                            $data['supplier_id']=$gather['compid'];
                            $data['supplier_name']=$gather['compname'];  
                            $data['status']=1; 
                            $data['price']=$product_datas['price'];
                            $data['pid']=$parent_id;
                            $data['imgarr']=$gather['main_imgs'];
                            $data['code']=$code['code'];
                            $data['video']=$gather['video'];
                            $data['turnover']=$gather['turnover'];;
                            $data['offerid']=$gather['offerid'];
                            $data['detail_url']=$product_datas['detailurl'];
                            $data['c_id']=0;
                            $data['user_id']=$gather['user_id'];
                            $data['product_link']='https://detail.1688.com/offer/'.$gather['offerid'].'.html';
                            if(isset($key['skuattr'][2])){
                                $data['option1']=$key['skuattr'][1];
                                $data['option2']=$key['skuattr'][2];
                            }else{
                                $data['option1']=$key['skuattr'][0];
                                $data['option2']=$key['skuattr'][1]??'';
                            } 
                            $datas[]=$data; 
                      }
                        
                   }
                     Db::name('products')->insertAll($datas);
                }
            }
            
            //采集表这里数据的状态设置为采集成功
            Db::name('gatherproduct')->where('offerid', $gather['offerid'])->update(array('status' => 1));
           Db::commit();
                 echo $gather['offerid'].'成功添加数据';die;
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                // 记录错误或返回错误信息
                print_r('处理失败'.$e->getMessage());die;
            }        

           }else{
                echo '没有需要更新的数据';die;
           }

        }
        //判断款号是否存在
        public static  function checksku($sku){
            $gather=Db::name('products')->where('localsku',$sku)->find();
            if($gather){
            return self::checksku($sku.chr(rand(65,90)));
            }else {
            return $sku;
            }
        }
         //有道翻译为英文    
        public static  function youdao($title){

            $youdao=ConfigModel::where('code','youdao')->value('values');                  
            $youdao = json_decode($youdao,true);              
            $app_secret=$youdao['app_secret'];   
            $app_key=$youdao['app_key'];                  
            $q = $title;
            $from = "zh-CHS";
            $to = "en";   
            $params = array('q' => $q,
                'from' => $from,
                'to' => $to
                );
            $params = add_auth_params($params, $app_key,$app_secret);                 
            $r = do_call('https://openapi.youdao.com/api', 'post', array(), $params, 'application/json');
            $r = json_decode($r,true);
            if(isset($r['translation'])){
                return $r['translation'][0];
            }else{
                return $title;
            }
        }
         
}

